package top.mable.payment.service;



import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.amqp.RabbitProperties;
import org.springframework.stereotype.Service;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Author wen
 * @Date 2021/7/7
 **/
@Slf4j
@Service
public class RabbitMqRetryTimeService {
    @Autowired
    private RabbitProperties rabbitProperties;

    public void retryControl(Message msg, Channel channel, Exception e) throws Exception {
        AtomicInteger time = new AtomicInteger(1);
        AtomicInteger timeTmp = (AtomicInteger) msg.getMessageProperties().getHeaders().putIfAbsent("RetryTime", time);
        log.info("RetryTime----------{}",timeTmp);
        if (timeTmp == null) {
            timeTmp = time;
        }
        RabbitProperties.ListenerRetry retry = rabbitProperties.getListener().getSimple().getRetry();
        if (timeTmp.get() >= rabbitProperties.getListener().getSimple().getRetry().getMaxAttempts() || !retry.isEnabled()) {
            channel.basicReject(msg.getMessageProperties().getDeliveryTag(), false);
            log.error("消息重试消费异常 id:{},{},{}", msg.getMessageProperties().getMessageId(), e.getMessage(), e);
            return;
        }
        timeTmp.incrementAndGet();
        throw e;
    }
}